import { useState, useEffect, useCallback } from 'react'
import useSWR from 'swr'

export interface PaginationParams {
  page: number
  limit: number
}

export interface PaginationResponse<T = unknown> {
  data: T[]
  total: number
  page: number
  limit: number
  totalPages: number
}

export interface UsePaginationOptions {
  initialPage?: number
  initialLimit?: number
  autoRetry?: boolean // 是否启用自动页码回退
  revalidateOnFocus?: boolean
  dedupingInterval?: number
  shouldRetryOnError?: boolean
}

export interface UsePaginationReturn<T = unknown> {
  data: T[]
  total: number
  page: number
  limit: number
  totalPages: number
  isLoading: boolean
  error: unknown
  setPage: (page: number) => void
  setLimit: (limit: number) => void
  nextPage: () => void
  prevPage: () => void
  goToPage: (page: number) => void
  refresh: () => void
  hasNextPage: boolean
  hasPrevPage: boolean
}

/**
 * 分页查询 Hook
 * @param apiFunction API函数，接收分页参数并返回Promise
 * @param options 配置选项
 * @returns 分页数据和操作方法
 */
export function usePagination<T = unknown>(
  apiFunction: (params: PaginationParams) => Promise<PaginationResponse<T>>,
  options: UsePaginationOptions = {}
) {
  const {
    initialPage = 1,
    initialLimit = 10,
    autoRetry = true,
    revalidateOnFocus = false,
    dedupingInterval = 1000,
    shouldRetryOnError = false,
  } = options

  const [page, setPageState] = useState(initialPage)
  const [limit, setLimitState] = useState(initialLimit)
  const [shouldRetry, setShouldRetry] = useState(false)

  // 生成SWR的key
  const swrKey = ['pagination', apiFunction.name, page, limit, shouldRetry]

  // 使用SWR进行数据获取
  const { data, error, isLoading, mutate } = useSWR(
    swrKey,
    () => apiFunction({ page, limit }),
    {
      revalidateOnFocus,
      dedupingInterval,
      shouldRetryOnError,
    }
  )

  // 自动页码回退逻辑
  useEffect(() => {
    if (
      autoRetry &&
      data &&
      page > 1 &&
      data.data.length === 0 &&
      !shouldRetry
    ) {
      // 当前页没有数据，自动回退到上一页
      setShouldRetry(true)
      setPageState(page - 1)
    } else if (shouldRetry) {
      // 重置重试标志
      setShouldRetry(false)
    }
  }, [data, page, autoRetry, shouldRetry])

  // 计算总页数
  const totalPages = data ? Math.ceil(data.total / limit) : 0

  // 设置页码
  const setPage = useCallback((newPage: number) => {
    if (newPage >= 1 && newPage <= totalPages) {
      setPageState(newPage)
    }
  }, [totalPages])

  // 设置每页数量
  const setLimit = useCallback((newLimit: number) => {
    if (newLimit > 0) {
      setLimitState(newLimit)
      setPageState(1) // 重置到第一页
    }
  }, [])

  // 下一页
  const nextPage = useCallback(() => {
    if (page < totalPages) {
      setPage(page + 1)
    }
  }, [page, totalPages, setPage])

  // 上一页
  const prevPage = useCallback(() => {
    if (page > 1) {
      setPage(page - 1)
    }
  }, [page, setPage])

  // 跳转到指定页
  const goToPage = useCallback((targetPage: number) => {
    setPage(targetPage)
  }, [setPage])

  // 刷新数据
  const refresh = useCallback(() => {
    mutate()
  }, [mutate])

  return {
    data: data?.data || [],
    total: data?.total || 0,
    page: data?.page || page,
    limit: data?.limit || limit,
    totalPages,
    isLoading,
    error,
    setPage,
    setLimit,
    nextPage,
    prevPage,
    goToPage,
    refresh,
    hasNextPage: page < totalPages,
    hasPrevPage: page > 1,
  }
} 